package com.gr.smartedubackend.controller;

import com.gr.smartedubackend.annotation.AuthCheck;
import com.gr.smartedubackend.common.BaseResponse;
import com.gr.smartedubackend.common.BusinessException;
import com.gr.smartedubackend.common.ErrorCode;
import com.gr.smartedubackend.constant.UserConstant;
import com.gr.smartedubackend.manager.CosManager;
import com.gr.smartedubackend.manager.FileManager;
import com.gr.smartedubackend.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

@RestController
@RequestMapping("/upload")
@Slf4j
public class FileUploadController {

    @Resource
    private CosManager cosManager;

    @Resource
    private FileManager fileManager;

    @PostMapping("/image")
    public BaseResponse<String> uploadImage(@RequestPart("file") MultipartFile multipartFile) {
        return ResultUtils.success(fileManager.uploadImage(multipartFile, "smart-edu"));
    }

    @PostMapping("/file")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile) {
        return ResultUtils.success(fileManager.uploadFile(multipartFile, "smart-edu"));
    }

    /**
     * 测试文件上传
     *
     * @param multipartFile
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        // 文件保存后的路径（不含域名）
        String filePath = String.format("/test/%s", fileName);
        File file = null;
        try {
            // 生成临时文件
            file = File.createTempFile(fileName, null);
            // 将上传文件写入临时文件
            multipartFile.transferTo(file);
            // 上传文件
            cosManager.putObject(filePath, file);
            // 返回可访问的地址
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("file upload error, filePath = " + filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filePath = {}", filePath);
                }
            }
        }

    }

}
